package filter;


import com.sun.deploy.net.HttpResponse;
import com.sun.net.httpserver.HttpExchange;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;


@WebFilter(filterName = "loginFilter")
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        //转换类型
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        //定义次数为0
        int i = 0;
        //验证是否登录，没有登录跳转到Login界面，登录则可以正常进行
        HttpSession session = req.getSession();
        String name_session = (String)session.getAttribute("name");

        //取出所有的cookiename
        ArrayList list = new ArrayList();
        //通过Cookie 获取cookie name
        Cookie[] cookies = req.getCookies();
        if(cookies != null){
            for (Cookie cookie : cookies){

                //存放name
                //读取中文
                list.add(URLDecoder.decode(cookie.getName(),"UTF-8"));
             }
        }

        //获取本网页路径
        String path = req.getServletPath();
//        resp.getWriter().println(path);
        //登录界面不进行拦截
        if(path.equals("/login")||path.equals("/register.jsp")||path.equals("/register")){
            //        完成过滤，继续执行
            chain.doFilter(req,resp);
        }
        else {
            //如果cookie 不为空，并且cookie 已经存在，则已经登录 可以放行
            if (cookies != null && cookieis(list,name_session) ) {
                // 完成过滤，继续执行
                chain.doFilter(req, resp);
            } else {
                //返回登录界面进行登录
                req.getRequestDispatcher("/login.jsp").forward(req, resp);
            }

        }


    }

    @Override
    public void destroy() {

    }
//判断是否存在指定cookie
    public boolean cookieis(ArrayList list,String name){
        boolean cookie_already = false;
        //循环判断
        for (Object cookie_name : list){
            if(cookie_name.equals(name)){
                cookie_already = true;
            }
        }

        return cookie_already;




    }
}
